# -*- coding: utf-8 -*-
# @Author : syc
# @Date   : 2019/7/9
# @File   : IC01_Past6MonQueryCnt.py
# @E-mail : shiyucen@bbdservice.com

'''eof
name:最近6个月的查询机构数
code:IC01_Past6MonQueryCnt
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
import  json
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = IC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def formatDate(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None

def IC01_Past6MonQueryCnt():
    try:
        six_month_ago = (datetime.datetime.now() - datetime.timedelta(days=6 * 30)).strftime("%Y%m%d")
        ICRRecordDetail = getTable('ICRRecordDetail')
        # print ICRRecordDetail

        if ICRRecordDetail is None:
            return u'缺失值1'
        elif ICRRecordDetail == [{}]:
            return 0
        reason_list=['贷款审批','信用卡审批']
        returnList = []

        for i in ICRRecordDetail:
            try:
                #查询原因
                queryReason=i.get('queryReason')
                #查询操作员
                querier=i.get('querier')

                #查询时间
                queryDate=i.get('queryDate')
                queryDateFormat = formatDate(queryDate)

                if queryReason in null_type_list or querier in null_type_list or queryDateFormat is None:
                    returnList.append(None)

                    continue
                if queryDateFormat >six_month_ago  and queryReason in reason_list :
                    returnList.append(querier)

                else:
                    returnList.append(0)

            except:

                returnList.append(None)
                # print returnList
                #
                continue
        returnSet = set(returnList)
        print returnSet
        returnListNotNone = filter(lambda x: x is not None, returnSet)
        # print returnListNotNone
        returnListNotZero = filter(lambda x: x != 0, returnListNotNone)
        # print returnListNotZero

        if len(returnListNotNone) == 0:
            return u"缺失值2"
        elif len(returnListNotZero) == 0:
            return 0
        else:
            return len(returnListNotZero)

    except:

        return u'缺失值3'

if __name__ == '__main__':
    file_obj = open(r'E:\\changjiang_bd\\IC_DSJ.json', 'r')
    content = file_obj.read()
    IC_DSJ = json.loads(content, strict=False)
    print IC01_Past6MonQueryCnt()


result = IC01_Past6MonQueryCnt()

